package com.study.handler;

import com.alibaba.fastjson.JSONObject;
import com.study.annotation.NotControllerResponseAdvice;
import com.study.pojo.common.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * Spring 中提供了一个类  ResponseBodyAdvice
 * 对 Controller 返回的内容在 HttpMessageConverter 进行类型转换之前拦截，
 * 进行相应的处理操作后，再将结果返回给客户端
 */

@RestControllerAdvice(basePackages = "com.study.controller")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    /**
     * 判断是否要交给 beforeBodyWrite 方法执行，ture：需要；false：不需要
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //注释了NotControllerResponseAdvice不进行包装
        //已经是Result类型的不需要包装了（说明已经包装上异常消息）

        return !(returnType.hasMethodAnnotation(NotControllerResponseAdvice.class)
                || returnType.getParameterType().isAssignableFrom(Result.class));
    }

    /**
     * 对 response 进行具体的处理,这里是封装成功的返回消息
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果body已经被包装了，就不进行包装
//        if (body instanceof Result) {
//            return body;
//        }

//        System.out.println(body);

        //是String类型的就特殊处理,手动将Result对象转化为Json字符串
        if (body instanceof String) {
            try {
                return JSONObject.toJSONString(Result.success(body));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return Result.success(body);
    }
}
